package com.tuo51.manager.controller;


import com.tuo51.childcare.repository.StoreItemRepository;
import com.tuo51.evaluate.domain.tags.RelObjectTag;
import com.tuo51.evaluate.domain.tags.Tag;
import com.tuo51.evaluate.repositories.article.ArticleListItemRepository;
import com.tuo51.evaluate.repositories.evaluatev2.EvaluateV2DimensionRepository;
import com.tuo51.evaluate.repositories.evaluatev2.EvaluateV2QuestionRepository;
import com.tuo51.evaluate.repositories.tags.RelObjectTagRepository;
import com.tuo51.evaluate.repositories.tags.TagRepository;
import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.model.MemVerificationCache;
import com.tuo51.foudation.model.StatusResponse;
import com.tuo51.manager.vo.TagObjectRelationVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

import static com.tuo51.foudation.constant.RequestConstant.TICKET;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 内容标签关系管理
 */
@RestController
@RequestMapping("/mapi/tag_relation")
@Api(value = "/mapi/tag_relation", tags = "OP - 内容标签关系管理")
public class MAPITagRelationController {

    @Autowired
    EvaluateV2QuestionRepository questionRepository;

    @Autowired
    EvaluateV2DimensionRepository dimensionRepository;

    @Autowired
    StoreItemRepository storeItemRepository;

    @Autowired
    private ArticleListItemRepository newsItemRepository;

    @Autowired
    private TagRepository tagRepository;

//    @Autowired
//    TagRelationRepository relationRepository;

    @Autowired
    RelObjectTagRepository relationRepository;

    @Autowired
    MemVerificationCache cache;

    @RequestMapping(value = "/list", method = GET)
    @ApiOperation(value = "资源列表, type，不传.所有 1.question  2. storeItem   3.dimension   4.newsItem")
    public StatusResponse list(@RequestHeader(TICKET) String ticket,
                               @RequestParam(value = "pageNum", required = false, defaultValue = "0")Integer pageNum,
                               @RequestParam(value = "pageSize", required = false, defaultValue = "15")Integer pageSize,
                               @RequestParam(value = "type", required = false)Integer type){

        cache.getStaffId(ticket);

        //先获取id列表
        List<RelObjectTag> relations = null;
        Long count = 0l;
        if (type != null){
            relations = relationRepository.findAllByObjTypeDistinctObjId(type,  pageNum * pageSize, pageSize);
            count = relationRepository.countAllByObjTypeDistinctObjId(type);
        }else {
            relations = relationRepository.findAllDistinctObjId(pageNum * pageSize, pageSize);
            count = relationRepository.countAllDistinctObjId();
        }


        List<TagObjectRelationVO> result = relations.stream().map(k->{

            List<Tag> tags = tagRepository.findAllByRelationObjId(k.getObjId(), k.getObjType());

            Object obj = null;
            switch (k.getObjType()){
                case 1: //question,
                    obj = questionRepository.getOne(k.getObjId());
                    break;
                case 2: //storeItem
                    obj = storeItemRepository.getOne(k.getObjId());
                    break;
                case 3:
                    obj = dimensionRepository.getOne(k.getObjId());
                    break;
                case 4:
                    obj = newsItemRepository.getOne(k.getObjId());
                    break;
            }

           return TagObjectRelationVO.of(k, obj, tags);
        }).collect(Collectors.toList());

        Page ret = new PageImpl<TagObjectRelationVO>(result, PageRequest.of(pageNum, pageSize), count);

        return StatusResponse.success(ret);
    }

    @RequestMapping(value = "/add", method = POST)
    @ApiOperation(value = "增加关系")
    public StatusResponse edit(@RequestHeader(TICKET) String ticket,
                               @RequestParam(value = "objId") String objId,
                               @RequestParam(value = "objType") Integer objType,
                               @RequestParam(value = "tagId") String tagId){
        cache.getStaffId(ticket);

        RelObjectTag ret = relationRepository.findByTagIdAndObjIdAndObjType(tagId, objId, objType);
        if (ret != null){
            return StatusResponse.error(ErrorCode.MOBILE_IS_EXIST, "记录已经存在");
        }

        Object obj = null;
        switch (objType){
            case 1: //question,
                obj = questionRepository.getOne(objId);
                break;
            case 2: //storeItem
                obj = storeItemRepository.getOne(objId);
                break;
            case 3:
                obj = dimensionRepository.getOne(objId);
                break;
            case 4:
                obj = newsItemRepository.getOne(objId);
                break;
        }
        if (obj == null){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "条目不存在");
        }

        Tag tag = tagRepository.getOne(tagId);
        if (tag == null){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "tag条目不存在");
        }

        RelObjectTag relation = new RelObjectTag();
        relation.setTagId(tagId);
        relation.setObjId(objId);
        relation.setObjType(objType);

        relationRepository.save(relation);

        return StatusResponse.success(relation);
    }


    @RequestMapping(value = "/delete", method = POST)
    @ApiOperation("删除")
    public StatusResponse delete(@RequestHeader(TICKET) String ticket,
                                 @RequestParam(value = "objId") String objId,
                                 @RequestParam(value = "objType") Integer objType,
                                 @RequestParam(value = "tagId") String tagId) {
        String staffId = cache.getStaffId(ticket);

        List<RelObjectTag> relations = relationRepository.findAllByObjIdAndObjTypeAndTagId(objId, objType, tagId);

        if (relations != null && relations.size() > 0){
            relationRepository.deleteInBatch(relations);
            return StatusResponse.success(relations.size());
        }else {
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "关系不存在");
        }

    }
}
